package course.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import course.pojo.entity.*;
import course.pojo.vo.*;
import course.service.*;
import course.service.impl.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author HLF
 * @date 2022/7/2 20:05
 */
@WebServlet("/teacher/teacherOwnController")
public class TeacherOwnController extends BaseController {
    private TeacherService teacherService = new TeacherServiceImpl();

    private TeaSubService teaSubService = new TeaSubServiceImpl();

    private SubjectService subjectService = new SubjectServiceImpl();

    private StuTeaService stuTeaService = new StuTeaServiceImpl();

    private StudentService studentService = new StudentServiceImpl();

    private ZhuanyeService zhuanyeService = new ZhuanyeServiceImpl();

    private CollegeService collegeService = new CollegeServiceImpl();


    /**
     * 跳转到教师管理课程页面
     * 页面需要的数据：所有课程信息，当前教师已经选择的课程信息
     * <p>
     * 教师管理课程
     * 教师选择自己教授的课程
     */
    protected void teaCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opn = req.getParameter("opn");
        String apn = req.getParameter("apn");
        if (StringUtils.isBlank(opn) || Integer.parseInt(opn) <= 0) {
            opn = "1";
        }
        if (StringUtils.isBlank(apn) || Integer.parseInt(apn) <= 0) {
            apn = "1";
        }
        this.index(req, resp, opn, apn);
    }

    protected void index(HttpServletRequest req, HttpServletResponse resp, String opn, String apn) throws ServletException, IOException {
        HttpSession session = req.getSession();

        //获取当前登录的teacher对象
        Teacher teacher = (Teacher) session.getAttribute("tteacher");

        //获取当前teacher已经选择的课程，并进行分页
        Page<Subject> ownSubjectPage = subjectService.ownPage(Integer.valueOf(opn), teacher.getTid());

        //获取所有课程信息,并进行分页
        Page<Subject> allSubjectPage = subjectService.page2(Integer.valueOf(apn), teacher.getCid());

        req.setAttribute("ownSubjectPage", ownSubjectPage);
        req.setAttribute("allSubjectPage", allSubjectPage);

        req.getRequestDispatcher("/teasub_manage.jsp").forward(req, resp);
    }

    /**
     * 教师选课
     */
    protected void order(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        int i = 0;

        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");
        Integer tid = teacher.getTid();
        String suid = req.getParameter("suid");
        TeaSub teaSub = teaSubService.getByTidAndSuid(tid, Integer.valueOf(suid));

        if (teaSub == null) {
            i = teaSubService.addTeaSub(new TeaSub(tid, Integer.valueOf(suid)));
        }

        writer.println(i);
        writer.flush();
    }

    /**
     * 退课
     * 教师退课之后，所有选过该教师对应该课程的学生自动取消选择该教师
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");
        Integer tid = teacher.getTid();
        String suid = req.getParameter("suid");

        int i = teaSubService.deleteByTidAndSuid(tid, Integer.valueOf(suid));

        //教师退课之后，所有选过该教师对应该课程的学生自动取消选择该教师
        stuTeaService.deleteByTidSuid(tid, Integer.valueOf(suid));


        if (i > 0) {
            this.teaCourse(req, resp);
        }
    }

    /**
     * 批量退课
     */
    protected void deleteSelect(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("ids[]");

        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");
        Integer tid = teacher.getTid();

        List<String> strings = Arrays.asList(ids);
        List<Integer> integers = strings.stream().map(Integer::valueOf).collect(Collectors.toList());

        int i = teaSubService.deleteSelect(integers, tid);

    }

    /**
     * 教师查看自己教授的每门课程对应的学生信息
     * 思路：从t_stu_tea表中查询出当前tid对应的suid
     */
    protected void ownstu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");
        Integer tid = teacher.getTid();


        List<TeaSub> byTid = teaSubService.getByTid(tid);
        List<TeaSubVo> teaSubVos = byTid.stream().map(teaSub -> {
            TeaSubVo teaSubVo = new TeaSubVo();
            try {
                BeanUtils.copyProperties(teaSubVo, teaSub);
                Subject subject = subjectService.getById(teaSub.getSuid());
                teaSubVo.setSuname(subject.getSuname());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return teaSubVo;
        }).collect(Collectors.toList());


        req.setAttribute("data", teaSubVos);
        req.getRequestDispatcher("/tea_ownstu.jsp").forward(req, resp);


        /*//按照suid将sid进行分组(获取每个suid对应的sid集合)
        //1.获取所有suid集合
        List<Integer> suids = null;
        try {
            suids = stuTeaService.getSuids(tid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //2.设置每一个suid对应的sid集合
        if (!suids.isEmpty()) {
            List<SuidSidRespVo> respVos = suids.stream().map(suid -> {
                SuidSidRespVo suidSidRespVo = new SuidSidRespVo();
                suidSidRespVo.setSuid(suid);
                Subject subject = subjectService.getById(suid);
                suidSidRespVo.setSuname(subject.getSuname());
                List<StudentRespVo> collect = stuTeaService.getByTidSuid(tid, suid).stream().map(stuTea -> {
                    Integer sid = stuTea.getSid();
                    Student student = studentService.getById(sid);
                    StudentRespVo studentRespVo = new StudentRespVo();
                    try {
                        BeanUtils.copyProperties(studentRespVo, student);
                        Zhuanye zhuanye = zhuanyeService.getById(student.getZid());
                        studentRespVo.setZname(zhuanye.getZname());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                    return studentRespVo;
                }).collect(Collectors.toList());

                suidSidRespVo.setStudents(collect);
                return suidSidRespVo;
            }).collect(Collectors.toList());


            req.setAttribute("data", respVos);
            req.getRequestDispatcher("/tea_ownstu.jsp").forward(req, resp);
        }else {
            req.setAttribute("data", null);
            req.getRequestDispatcher("/tea_ownstu.jsp").forward(req, resp);
        }*/

    }

    protected void stus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String suid = req.getParameter("suid");

        if (Integer.parseInt(suid) == -1) {
            req.setAttribute("suidSidRespVo", new SuidSidRespVo());
            this.ownstu(req, resp);
        }

        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");
        Integer tid = teacher.getTid();

        SuidSidRespVo suidSidRespVo = new SuidSidRespVo();
        suidSidRespVo.setSuid(Integer.valueOf(suid));
        Subject subject = subjectService.getById(Integer.valueOf(suid));
        suidSidRespVo.setSuname(subject.getSuname());
        List<StudentRespVo> collect = stuTeaService.getByTidSuid(tid, Integer.valueOf(suid)).stream().map(stuTea -> {
            Integer sid = stuTea.getSid();
            Student student = studentService.getById(sid);
            StudentRespVo studentRespVo = new StudentRespVo();
            try {
                BeanUtils.copyProperties(studentRespVo, student);
                Zhuanye zhuanye = zhuanyeService.getById(student.getZid());
                studentRespVo.setZname(zhuanye.getZname());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            return studentRespVo;
        }).collect(Collectors.toList());

        suidSidRespVo.setStudents(collect);


        req.setAttribute("suidSidRespVo", suidSidRespVo);
        this.ownstu(req, resp);
    }

    /**
     * 跳转到教师个人中心
     */
    protected void centerPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");

        TeacherRespVo teacherRespVo = new TeacherRespVo();
        try {
            BeanUtils.copyProperties(teacherRespVo, teacher);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        teacherRespVo.setCname(collegeService.getById(teacher.getCid()).getCname());

        req.setAttribute("teacherVo", teacherRespVo);
        req.getRequestDispatcher("/teacher_center.jsp").forward(req, resp);
    }

    /**
     * 修改基本信息
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tid = req.getParameter("tid");
        String tsex = req.getParameter("tsex");
        String tphone = req.getParameter("tphone");
        String temail = req.getParameter("temail");
        String tpassword2 = req.getParameter("tpassword2");//新密码

        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");

        if (StringUtils.isNotBlank(tsex) && StringUtils.isNotBlank(tphone) && StringUtils.isNotBlank(temail)) {
            teacher.setTsex(tsex);
            teacher.setTphone(tphone);
            teacher.setTemail(temail);
        }
        if (StringUtils.isNotBlank(tpassword2)) {
            //设置新密码并加密
            String bcrypt = DigestUtil.bcrypt(tpassword2);
            teacher.setTpassword(bcrypt);
        }

        teacher.setTid(Integer.valueOf(tid));

        int i = teacherService.updateInfo(teacher);

        session.setAttribute("tteacher", teacher);
        this.centerPage(req, resp);
    }


    /**
     * 验证密码：
     * 1.原密码或新密码为空
     * 2.原密码错误
     * 3.两次密码不一致
     */
    protected void pass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        String tpassword = req.getParameter("tpassword");
        String tpassword2 = req.getParameter("tpassword2");
        String tpassword3 = req.getParameter("tpassword3");

        Map<String, Object> result = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        if (StringUtils.isBlank(tpassword) || StringUtils.isBlank(tpassword2) || StringUtils.isBlank(tpassword3)) {
            result.put("code", 0);
            result.put("msg", "原密码或新密码不能为空");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
            return;
        }

        if (!tpassword2.equalsIgnoreCase(tpassword3)) {
            result.put("code", 0);
            result.put("msg", "两次密码不一致！");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
            return;
        }

        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("tteacher");

        //将密文进行对比
        boolean check = DigestUtil.bcryptCheck(tpassword, teacher.getTpassword());
        if (!check) {
            result.put("code", 0);
            result.put("msg", "原密码错误！");
            String s = mapper.writeValueAsString(result);
            writer.println(s);
        }
    }

}
